<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>销售记录管理</title>
    <script src="/js/vue.js"></script>
    <link type="text/css" rel="stylesheet" href="/css/index.css">
    <script src="/js/index.js"></script>
    <script src="/js/axios.min.js"></script>
</head>
<body>
<div id="app">
    <el-card shadow="hover" style="margin: 10px;">
        <el-row :gutter="10" style="margin-bottom: 10px;">
            <el-col :span="4">
                <el-input size="mini" v-model="searchForm.orderNo" placeholder="订单号"></el-input>
            </el-col>
            <el-col :span="4">
                <el-input size="mini" v-model="searchForm.ticketName" placeholder="门票名称"></el-input>
            </el-col>
            <el-col :span="4">
                <el-date-picker size="mini" v-model="searchForm.salePlacetime" type="date" placeholder="下单时间"></el-date-picker>
            </el-col>
            <el-col :span="4">
                <el-select size="mini" v-model="searchForm.saleIsvalid" placeholder="是否有效">
                    <el-option label="有效" value="1"></el-option>
                    <el-option label="无效" value="0"></el-option>
                </el-select>
            </el-col>
            <el-col :span="4">
                <el-button size="mini" icon="el-icon-search" type="primary" @click="search">搜索</el-button>
                <el-button size="mini" type="success" @click="handleAdd">新增销售记录</el-button>
            </el-col>
        </el-row>

        <el-table :data="tableData" border stripe style="width: 100%">
            <el-table-column prop="saleId" label="ID" width="60"></el-table-column>
            <el-table-column prop="scenicName" label="景区名称"></el-table-column>
            <el-table-column prop="ticketName" label="门票名称"></el-table-column>
            <el-table-column prop="orderNo" label="订单号"></el-table-column>
            <el-table-column prop="ticketSprice" label="单价"></el-table-column>
            <el-table-column prop="ticketScount" label="数量"></el-table-column>
            <el-table-column prop="ticketTprice" label="总价"></el-table-column>
            <el-table-column prop="salePlacetime" label="下单时间"></el-table-column>
            <el-table-column prop="salePicktime" label="取票时间"></el-table-column>
            <el-table-column prop="saleIsvalid" label="是否有效">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.saleIsvalid === '1' ? 'success' : 'danger'">
                        {{ scope.row.saleIsvalid === '1' ? '有效' : '无效' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                style="margin-top: 10px; text-align: right;">
        </el-pagination>
    </el-card>

    <!-- 新增/编辑销售记录弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="50%">
        <el-form :model="form" :rules="rules" ref="form" label-width="120px">
            <el-form-item label="订单号" prop="orderNo">
                <el-input v-model="form.orderNo" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="景区名称" prop="scenicName">
                <el-input v-model="form.scenicName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="门票名称" prop="ticketName">
                <el-input v-model="form.ticketName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="单价" prop="ticketSprice">
                <el-input v-model.number="form.ticketSprice" autocomplete="off" placeholder="请输入小数"></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="ticketScount">
                <el-input v-model.number="form.ticketScount" autocomplete="off" placeholder="请输入数字"></el-input>
            </el-form-item>
            <el-form-item label="总价" prop="ticketTprice">
                <el-input v-model.number="form.ticketTprice" autocomplete="off" placeholder="请输入小数"></el-input>
            </el-form-item>
            <el-form-item label="下单时间" prop="salePlacetime">
                <el-date-picker v-model="form.salePlacetime" type="date" placeholder="选择下单时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="取票时间" prop="salePicktime">
                <el-date-picker v-model="form.salePicktime" type="date" placeholder="选择取票时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="是否有效" prop="saleIsvalid">
                <el-select v-model="form.saleIsvalid" placeholder="选择状态">
                    <el-option label="有效" value="1"></el-option>
                    <el-option label="无效" value="0"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
            <el-button type="primary" @click="submitForm('form')">确定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    // 日期格式化函数
    function formatDate(date) {
        if (!date) return '';
        const d = new Date(date);
        let month = '' + (d.getMonth() + 1);
        let day = '' + d.getDate();
        const year = d.getFullYear();

        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;

        return [year, month, day].join('-');
    }

    new Vue({
        el: '#app',
        data() {
            return {
                tableData: [],
                currentPage: 1,
                pageSize: 10,
                total: 0,
                searchForm: {},
                dialogFormVisible: false,
                title: '添加销售记录',
                isEdit: false,
                form: {
                    saleId: '',
                    scenicName: '',
                    ticketName: '',
                    orderNo: '',
                    ticketSprice: null,
                    ticketScount: null,
                    ticketTprice: null,
                    salePlacetime: '',
                    salePicktime: '',
                    saleIsvalid: ''
                },
                rules: {
                    orderNo: [
                        { required: true, message: '请输入订单号', trigger: 'blur' }
                    ],
                    scenicName: [
                        { required: true, message: '请输入景区名称', trigger: 'blur' }
                    ],
                    ticketName: [
                        { required: true, message: '请输入门票名称', trigger: 'blur' }
                    ],
                    ticketSprice: [
                        { required: true, message: '请输入单价', trigger: 'blur' },
                        { type: 'number', message: '单价必须为数字', trigger: 'blur' }
                    ],
                    ticketScount: [
                        { required: true, message: '请输入数量', trigger: 'blur' },
                        { type: 'number', message: '数量必须为数字', trigger: 'blur' }
                    ],
                    ticketTprice: [
                        { required: true, message: '请输入总价', trigger: 'blur' },
                        { type: 'number', message: '总价必须为数字', trigger: 'blur' }
                    ],
                    salePlacetime: [
                        { required: true, message: '请选择下单时间', trigger: 'change' }
                    ],
                    salePicktime: [
                        { required: true, message: '请选择取票时间', trigger: 'change' }
                    ],
                    saleIsvalid: [
                        { required: true, message: '请选择是否有效', trigger: 'change' }
                    ]
                }
            }
        },
        created() {
            this.searchForm = {};          // 必须清空
            this.currentPage = 1;
            this.loadData();
        },
        methods: {
            // 加载销售记录列表
            loadData() {
                const searchParams = {};
                if (this.searchForm.orderNo) searchParams.orderNo = this.searchForm.orderNo;
                if (this.searchForm.ticketName) searchParams.ticketName = this.searchForm.ticketName;
                if (this.searchForm.salePlacetime) searchParams.salePlacetime = formatDate(this.searchForm.salePlacetime);
                if (this.searchForm.saleIsvalid) searchParams.saleIsvalid = this.searchForm.saleIsvalid;

                axios.post('/sale/queryByPage', {
                    pageNo: this.currentPage,
                    pageSize: this.pageSize,
                    data: searchParams
                })
                        .then(res => {
                            if (res.data.code === 200) {
                                this.tableData = res.data.data.list;
                                this.total = res.data.data.total;
                            } else {
                                this.$message.error('加载失败：' + res.data.message);
                            }
                        })
                        .catch(err => {
                            console.error(err);
                            this.$message.error('网络错误或接口异常');
                        });
            },
            // 分页大小变更
            handleSizeChange(val) {
                this.pageSize = val;
                this.loadData();
            },
            // 当前页码变更
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },
            // 搜索销售记录
            search() {
                this.currentPage = 1;
                this.loadData();
            },
            // 提交销售记录表单（新增/编辑）
            submitForm(formRef) {
                this.$refs[formRef].validate(valid => {
                    if (valid) {
                        // 处理表单数据，确保日期格式正确
                        const submitForm = {
                            ...this.form,
                            salePlacetime: this.form.salePlacetime ? formatDate(this.form.salePlacetime) : '',
                            salePicktime: this.form.salePicktime ? formatDate(this.form.salePicktime) : ''
                        };

                        const uri = this.isEdit ? '/sale/update' : '/sale/insert';
                        const method = this.isEdit ? 'put' : 'post';
                        axios[method](uri, submitForm)
                                .then(response => {
                                    if (response.data.code === 200) {
                                        this.$message.success('操作成功');
                                        this.loadData();
                                        this.dialogFormVisible = false;
                                    } else {
                                        this.$message.error('操作失败：' + (response.data.message || '未知错误'));
                                    }
                                })
                                .catch(error => {
                                    console.error(error);
                                    this.$message.error('网络错误或接口不支持当前请求方法: ' + error.message);
                                });
                    } else {
                        this.$message.warning('表单验证失败，请检查输入');
                        return false;
                    }
                });
            },
            // 重置表单
            resetForm(formRef) {
                const ref = this.$refs[formRef];
                if (ref) {
                    ref.clearValidate();
                    ref.resetFields();
                    this.form = {
                        saleId: '',
                        scenicName: '',
                        ticketName: '',
                        orderNo: '',
                        ticketSprice: null,
                        ticketScount: null,
                        ticketTprice: null,
                        salePlacetime: '',
                        salePicktime: '',
                        saleIsvalid: ''
                    };
                }
            },
            // 打开新增销售记录弹窗
            handleAdd() {
                this.dialogFormVisible = true;
                this.title = '添加销售记录';
                this.isEdit = false;
                this.form = {
                    saleId: '',
                    scenicName: '',
                    ticketName: '',
                    orderNo: '',
                    ticketSprice: null,
                    ticketScount: null,
                    ticketTprice: null,
                    salePlacetime: '',
                    salePicktime: '',
                    saleIsvalid: ''
                };
                this.$nextTick(() => this.$refs.form && this.$refs.form.clearValidate());
            },
            // 打开编辑销售记录弹窗
            handleEdit(index, row) {
                this.dialogFormVisible = true;
                this.title = '编辑销售记录';
                this.isEdit = true;
                this.form = JSON.parse(JSON.stringify(row));
                // 处理日期格式（后端返回字符串转Date）
                if (row.salePlacetime) this.form.salePlacetime = new Date(row.salePlacetime);
                if (row.salePicktime) this.form.salePicktime = new Date(row.salePicktime);
                this.$nextTick(() => this.$refs.form && this.$refs.form.clearValidate());
            },
            // 删除销售记录
            handleDelete(index, row) {
                this.$confirm('此操作将永久删除该销售记录，是否继续？', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`/sale/deleteById?saleId=${row.saleId}`)
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.$message.success('删除成功');
                                    this.loadData();
                                } else {
                                    this.$message.error('删除失败：' + (response.data.message || '未知错误'));
                                }
                            })
                            .catch(error => {
                                console.error(error);
                                this.$message.error('删除失败，请检查接口: ' + error.message);
                            });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            }
        }
    })
</script>
</body>
</html>